<?php
namespace app\interfaces\behavior;

use think\Config;
use think\Request;
use think\Response;
use Lcobucci\JWT\Parser;

class Jwt
{
    public function run(&$params)
    {

        $token = Request::instance()->header('token', null);

        if (empty($token)) {
            abort(Response::create(['code' => 500, 'message' => 'token不存在'], 'json'));
        }

        $token = (new Parser())->parse($token); // Parses from a string

        // 验证 token
        if (Config::get('token.secret') != $token->getClaim('secret')) {

            abort(Response::create(['code' => 501, 'message' => 'token验证失败'], 'json'));
        }

        // 验证有效期
        if (time() >= $token->getClaim('exp')) {

            abort(Response::create(['code' => 502, 'message' => 'token已过期,请您重新登录'], 'json'));

        }

    }
}
